<template>
  <div>
    <a-upload
      name="avatar"
      listType="picture-card"
      class="avatar-uploader"
      :showUploadList="false"
      :beforeUpload="beforeUpload"
      @change="handleChange"
    >
      <img
        class="default-img"
        :src="imageUrl ? imageUrl : require('../../../assets/images/avatar.png')"
        alt="avatar"
      />
    </a-upload>

    <!-- modal -->
    <cropperModal ref="cropperModal" @ok="handleCropperSuccess"></cropperModal>
  </div>
</template>
<script>
import cropperModal from "./cropper";
import { uploadAvatar } from "@/api/login";
export default {
  components: {
    cropperModal,
  },
  props: {
    //图片格式
    imgFormat: {
      type: Array,
      default: function () {
        return ["image/jpeg", "image/png", "image/jpg"];
      },
    },
    //图片大小
    imgSize: {
      type: Number,
      default: 2,
    },
    //图片裁切配置
    options: {
      type: Object,
      default: function () {
        return {
        };
      },
    },
    //回显图片路径
    photoUrl: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      imageUrl: "",
    };
  },
  watch: {
    photoUrl: {
      handler(val) {
        this.imageUrl = val || "";
      },
      immediate: true,
    },
  },
  methods: {
    //从本地选择文件
    handleChange(info) {
      let { options } = this;
      let imgName = "avatar-" + info.file.uid;
      this.getBase64(info.file.originFileObj).then((imageUrl) => {
        let target = Object.assign({}, options, {
          img: imageUrl,
        });
        this.$refs["cropperModal"].edit(target, imgName);
      });
    },
    // 上传之前 格式与大小校验
    beforeUpload(file) {
      let { imgFormat, imgSize } = this;
      console.log("fileType:", file.type)
      let isFormat = imgFormat.includes(file.type);
      if (!isFormat) {
        this.$message.destroy();
        this.$message.error("图片格式不支持！");
      }
      const isLt2M = file.size / 1024 / 1024 <= imgSize;
      if (!isLt2M) {
        this.$message.destroy();
        this.$message.error("图片大小限制在" + imgSize + "MB内!");
      }
      return isFormat && isLt2M;
    },
    //裁剪成功后的File对象
    handleCropperSuccess(data) {
      //进行图片上传动作
      // 模拟后端请求 2000 毫秒延迟
      let that = this;
      let formData = new FormData();
      formData.append("multipartFile", data);
      uploadAvatar(formData)
        .then((res) => {
          if (res) {
            that.$message.success("头像修改成功~");
            that.imageUrl = res.data.msg;
            that.$emit("ok", this.imageUrl);
            that.$store.commit("SET_USERINFO", { photo: this.imageUrl });
          }
        })
        .catch((err) => {
          that.$message.destroy();
          that.$message.success("头像修改失败！", err);
        });
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file); //开始转
        reader.onload = function () {
          fileResult = reader.result;
        }; //转 失败
        reader.onerror = function (error) {
          reject(error);
        }; //转 结束  咱就 resolve 出去
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
  },
};
</script>
<style lang='stylus' scoped>
.avatar-uploader > .ant-upload
  width 200px
  height 200px
.avatar-uploader .default-img
  width 100%
  border-radius 50%
.ant-upload-select-picture-card i
  font-size 32px
  color #999
.ant-upload-select-picture-card .ant-upload-text
  margin-top 8px
  color #666
</style>